package com.foreknow.dao.impl;

import com.foreknow.bean.Book;
import com.foreknow.bean.Borrow_info;
import com.foreknow.bean.Category;
import com.foreknow.bean.Student;
import com.foreknow.dao.Borrow_infoDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;

import java.util.List;

public class Borrow_infoDaoImpl extends BaseDao implements Borrow_infoDao {
    @Override
    public boolean Insert(Borrow_info borrow_info, Book book, Student student) {
        String sql="insert into borrow_info(book_id,student_id,start_time,end_time) \n" +
                "select b.id,s.id,?,? \n" +
                "FROM book b,student s where b.name=? and s.name=?";
        int isRight = jdbcTemplate.update(sql,borrow_info.getStart_time(),borrow_info.getEnd_time(),book.getName(),student.getName());
        return isRight==1;
    }

    @Override
    public List<Object> Query(Category category) {
        String sql = "SELECT borrow_info.id,book.name as book_name,student.name as student_name,start_time,end_time FROM \n" +
                " borrow_info,book,student,(SELECT id FROM book WHERE category_id = (SELECT id FROM category WHERE name = ?)) Bid\n" +
                "WHERE borrow_info.book_id = Bid.id and book.id = borrow_info.book_id and student.id = borrow_info.student_id";
        MappingFactory mappingFactory = MappingFactory.getInstance();
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.BORROW_INFO_SELECT_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,mapping,category.getName());
        return list;
    }

    @Override
    public boolean Delete() {
        String sql="DELETE b FROM borrow_info b,(SELECT MAX(id) as max_id FROM borrow_info) Did\n" +
                "WHERE b.id = Did.max_id";
        int isRight = jdbcTemplate.update(sql);
        return isRight==1;
    }
}
